const {app, ipcMain, BrowserWindow, Menu, protocol} = require('electron');
const path = require("path");
const fs = require('fs');
const dotenv = require('dotenv');
const {getLocalIP, ChatService, callGo} = require("./main_function");

dotenv.config();

process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true';


let fileBoxWindow = null



const logFile = fs.createWriteStream('app.log', { flags: 'w' });
const logStdout = process.stdout;

console.log = message => {
    logFile.write(`${message}\n`);
    logStdout.write(`${message}\n`);
};
console.error = message => {
    logFile.write(`ERROR: ${message}\n`);
    logStdout.write(`ERROR: ${message}\n`);
};



// 创建文件对话框窗口
const createWindowFileBox = (event) => {
    fileBoxWindow = new BrowserWindow({
        icon: path.join(app.getAppPath(), 'resource/shortcut.ico'),
        width: 640,
        height: 480,
        roundedCorners: true,
        parent: BrowserWindow.fromWebContents(event.sender),
        modal: true,
        webPreferences: {
            preload: path.join(app.getAppPath(), 'preload.js'),
            webviewTag: true,
            webAssembly: true,
        }
    });

    // if (process.env.VITE_DEV_SERVER_URL) {
    //     fileBoxWindow.loadURL(process.env.VITE_DEV_SERVER_URL + "#create");
    // } else {
    //     // 使用自定义协议
    //     fileBoxWindow.loadURL('app://dist/index.html#create');
    // }

    fileBoxWindow.on('closed', () => {
        fileBoxWindow = null;
    });
};

const createWindow = () => {
    const win = new BrowserWindow({
        icon: path.join(app.getAppPath(), 'resource/shortcut.ico'),
        width: 1080,
        height: 720,
        minWidth: 540,
        minHeight: 360,
        roundedCorners: true,

        webPreferences: {
            preload: path.join(app.getAppPath(), 'preload.js'),
            webviewTag: true, // 启用 webview 标签
            webAssembly: true, // 启用 WebAssembly
        }
    });

    console.log(">>> app.getAppPath() = ", app.getAppPath())

    if (process.env.VITE_DEV_SERVER_URL) {
        win.loadURL(process.env.VITE_DEV_SERVER_URL);
        win.webContents.openDevTools();
    } else {
        // 使用自定义协议
        win.loadFile(path.join(app.getAppPath(), 'dist/index.html')); // 正确
    }

    // 监听页面加载完成事件
    win.webContents.on('did-finish-load', () => {
        console.log("监听页面加载完成...")
    });

    chatService = new ChatService((message) => {
        // console.log("message= ",message);
        win.webContents.send('chat-receive', message);
    });
    chatService.start();

    stdInputFun = callGo((message) => {
        win.webContents.send('file-stdout', message);
    })
};

Menu.setApplicationMenu(null)

app.whenReady().then(() => {
    createWindow();
    app.on('activate', () => {
        if (BrowserWindow.getAllWindows().length === 0) createWindow();
    });

});

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        if (stdInputFun) stdInputFun('exit');
        chatService?.stop();
        app.quit();
    }
});

let chatService;
let stdInputFun;

//发送后可以响应（推荐使用）：invoke+handle UI线程 ——> Main线程
ipcMain.handle("localIp", (event) => getLocalIP())
ipcMain.handle("chat-openSend", (event, remoteIp) => chatService.chatSend("[ping]", remoteIp))
ipcMain.handle("chat-updSend", (event, message, remoteIp) => chatService.chatSend(message, remoteIp))
ipcMain.handle("file-send", (event, id, filepath) => stdInputFun(`[add-${id}] ${filepath}`))
ipcMain.handle("file-open", (event, remoteIp) => stdInputFun(`[open] ${remoteIp}`))

ipcMain.handle("open-file-box", (event) => {
    if (!fileBoxWindow) {
        createWindowFileBox(event);
        return true;
    }
    return false; // 返回值将会被传递给invoke调用
})

